package com.light.gulimall.order.listener;

import com.light.common.to.SecKillRabbitTO;
import com.light.gulimall.order.entity.OrderEntity;
import com.light.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class MyRabbitListener {

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "order.release.order.queue")
    public void releaseOrder(OrderEntity order, Message message, Channel channel) throws IOException {
        log.info("接收到关单请求，订单号:{}",order.getOrderSn());
        try {
            orderService.doReleaseOrder(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitListener(queues = "order.seckill.order.queue")
    public void seckillOrder(SecKillRabbitTO secKillRabbitTO, Message message, Channel channel) throws IOException {
        log.info("接收到秒杀创建订单请求，订单号:{}",secKillRabbitTO.getOrderNo());
        try {
            orderService.createSecKillOrder(secKillRabbitTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

}
